package foundation.tree.binaryTree;

import java.util.HashMap;
import java.util.Map;

/**
 * @author hang an
 * @since 2025/7/13
 */
public class 从前序与中序遍历序列构造二叉树 {
    Map<Integer, Integer> map = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return f(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    public TreeNode f(int[] preorder, int l1, int r1, int[] inorder, int l2, int r2) {
        if (l1 > r1) return null;
        TreeNode head = new TreeNode(preorder[l1]);
        if (l1 == r1) return head;
        int find = map.get(preorder[l1]);
        head.left = f(preorder, l1 + 1, l1 + find - l2, inorder, l2, find - 1);
        head.right = f(preorder, l1 + find - l2 + 1, r1, inorder, find + 1, r2);
        return head;
    }
}
